<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 赠卷
 */
class Givev extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('givev')
            ->setDescription('每个月赠卷活动');
    }

    //先写定时任务，后期用户量多了改队列
    protected function execute(Input $input, Output $output)
    {
        $cursor = Db::name('return_volume')->where('sy_count', '>', 0)->cursor();
        foreach ($cursor as $user) {
            $uid = $user['uid'];
            $r_id = $user['id'];
            $is_current_month_give = Db::name('return_volume_record')
                ->where(['uid' => $uid, 'r_id' => $r_id])->whereMonth('create_time')
                ->value('id');
            if (!$is_current_month_give) { //当月没有赠送
                Db::startTrans();
                try {
                    if ($user['sy_count'] > $user['month_count']) {
                        $give_real_count = $user['month_count'];
                    } else {
                        $give_real_count = $user['sy_count'];
                    }
                    Db::name('return_volume_record')->insert(
                        ['uid' => $uid, 'r_id' => $r_id, 'num' => $give_real_count, 'amount' => $user['amount'], 'create_time' => time()]
                    );
                    for ($i = 0; $i < $give_real_count; $i++) {
                        Db::name('user_coupon')->insert(
                            ['user_id' => $uid, 'coupon_id' => 0, 'coupon_name' => '立减卷', 'coupon_icon' => '', 'coupon_type' => 2, 'start_time' => time(),
                                'end_time' => strtotime("+30 day"), 'used_amount' => $user['amount'], 'receive_time' => time(),
                            ]
                        );
                    }
                    Db::name('return_volume')->where('id', $user['id'])->dec('sy_count', $give_real_count)->update();
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }
            }
        }
    }
}
